﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;

namespace BurningSphere.Simulator
{
    static class MeshHelper
    {
        public static void DumpVertices(Mesh mesh)
        {
            Debug.WriteLine("Vertices");
            using (VertexBuffer vb = mesh.VertexBuffer)
            {
                CustomVertex.PositionNormal[] verts = (CustomVertex.PositionNormal[])vb.Lock(0, typeof(CustomVertex.PositionNormal), LockFlags.None, mesh.NumberVertices);
                {
                    try
                    {
                        for (int i = 0; i < verts.Length; i++)
                        {
                            Debug.WriteLine("Vert " + i + ": " + verts[i].X + ", " + verts[i].Y + ", " + verts[i].Z);
                        }
                    }
                    finally
                    {
                        vb.Unlock();
                    }
                }

            }
        }

        /// <summary>
        /// Returns a radius and a center point for a sphere which contains the mesh. Not that this method
        /// will lock the mesh to read the vertices and therefore may have performance implications.
        /// </summary>
        /// <param name="mesh">The Mesh to contain</param>
        /// <param name="center">return value - center point of bounding sphere</param>
        /// <returns>radius of the bounding sphere.</returns>
        public static float ComputeBoundingSphere(Mesh mesh, out Vector3 center)
        {
            Debug.Assert(mesh != null);

            // Lock the vertex buffer
            GraphicsStream data = null;
            try
            {
                data = mesh.LockVertexBuffer(LockFlags.ReadOnly);
                // Now compute the bounding sphere
                return Geometry.ComputeBoundingSphere(data, mesh.NumberVertices,
                    mesh.VertexFormat, out center);
            }
            finally
            {
                // Make sure to unlock the vertex buffer
                if (data != null)
                {
                    mesh.UnlockVertexBuffer();
                }
            }
        }

    }
}
